import json
import os
from datetime import datetime

class LearningMemory:
    """学习记忆类"""
    def __init__(self, student_id):
        self.student_id = student_id
        self.memory_file = f"data/learning_memory_{student_id}.json"
        # 初始化掌握程度字典
        self.mastery_levels = {}
        # 加载记忆（包括答案和掌握程度）
        self.answers = self.load_memory()
        # 初始化尚未设置的知识点掌握程度
        self._initialize_mastery_levels()
        
    def _initialize_mastery_levels(self):
        """初始化尚未设置的知识点的掌握程度为0"""
        for kp_id in self.answers:
            # 只初始化尚未设置的知识点
            if kp_id not in self.mastery_levels:
                self.mastery_levels[kp_id] = 0
    
    def load_memory(self):
        """加载学习记忆和掌握程度"""
        try:
            if os.path.exists(self.memory_file):
                with open(self.memory_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    # 检查数据格式
                    if isinstance(data, dict):
                        # 新版本格式：有answers和mastery_levels字段
                        if "answers" in data:
                            # 加载掌握程度
                            if "mastery_levels" in data:
                                self.mastery_levels = data["mastery_levels"]
                            return data["answers"]
                        # 旧版本格式：直接是answers字典
                        else:
                            return data
        except Exception as e:
            print(f"加载学习记忆失败: {e}")
        return {}
    
    def save_memory(self):
        """保存学习记忆和掌握程度"""
        try:
            # 将掌握程度合并到answers中以便保存
            memory_data = {
                "answers": self.answers,
                "mastery_levels": self.mastery_levels
            }
            with open(self.memory_file, 'w', encoding='utf-8') as f:
                json.dump(memory_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存学习记忆失败: {e}")
    
    def record_answer(self, knowledge_point_id, is_correct, question_text=None):
        """记录答题情况并更新掌握程度"""
        if knowledge_point_id not in self.answers:
            self.answers[knowledge_point_id] = []
            # 新知识点初始掌握程度为0
            if knowledge_point_id not in self.mastery_levels:
                self.mastery_levels[knowledge_point_id] = 0
        
        # 记录最近10次答题情况
        record = {
            "timestamp": datetime.now().isoformat(),
            "is_correct": is_correct
        }
        
        # 如果提供了题目内容，也记录下来
        if question_text:
            record["question_text"] = question_text
        
        self.answers[knowledge_point_id].append(record)
        
        # 只保留最近10次记录
        if len(self.answers[knowledge_point_id]) > 10:
            self.answers[knowledge_point_id] = self.answers[knowledge_point_id][-10:]
        
        # 更新掌握程度：正确加5分，错误减5分，范围0-100
        if is_correct:
            self.mastery_levels[knowledge_point_id] = min(100, self.mastery_levels[knowledge_point_id] + 5)
        else:
            self.mastery_levels[knowledge_point_id] = max(0, self.mastery_levels[knowledge_point_id] - 5)
        
        # 保存记忆
        self.save_memory()
    
    def get_accuracy(self, knowledge_point_id):
        """获取知识点的正确率"""
        if knowledge_point_id not in self.answers or not self.answers[knowledge_point_id]:
            return 0.5  # 默认中等难度
        
        # 计算最近10次的正确率
        recent_answers = self.answers[knowledge_point_id][-10:]
        correct_count = sum(1 for ans in recent_answers if ans["is_correct"])
        return correct_count / len(recent_answers)
    
    def get_knowledge_point_status(self):
        """获取所有知识点的学习状态，包括掌握程度"""
        status = {}
        for kp_id, answers in self.answers.items():
            if answers:
                correct_count = sum(1 for ans in answers if ans["is_correct"])
                # 获取掌握程度，如果没有则设置为0
                mastery_level = self.mastery_levels.get(kp_id, 0)
                status[kp_id] = {
                    "total_attempts": len(answers),
                    "correct_attempts": correct_count,
                    "accuracy": correct_count / len(answers),
                    "mastery_level": mastery_level
                }
        return status
    
    def get_mastery_level(self, knowledge_point_id):
        """获取指定知识点的掌握程度"""
        return self.mastery_levels.get(knowledge_point_id, 0)